package com.jshongli.myapplication.inspect;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnDismissListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.jshongli.myapplication.R;
import com.jshongli.myapplication.base.BaseActivity;
import com.jshongli.myapplication.common.callback.ResponseCallback;
import com.jshongli.myapplication.common.utils.AccountManager;
import com.jshongli.myapplication.common.utils.AppManager;
import com.jshongli.myapplication.common.utils.DateUtils;
import com.jshongli.myapplication.common.utils.MyDialog;
import com.jshongli.myapplication.common.utils.ParseUtils;
import com.jshongli.myapplication.common.utils.ToastUtils;
import com.jshongli.myapplication.common.utils.URLUtils;
import com.jshongli.myapplication.common.utils.UtilPreferences;
import com.jshongli.myapplication.model.inspect.EventBean;
import com.jshongli.myapplication.model.inspect.InspectBean;
import com.jshongli.myapplication.model.task.TaskBean;
import com.jshongli.myapplication.task.TaskDetailActivity;
import com.jshongli.myapplication.task.TaskReplyActivity;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Request;

public class AgentmaintenanceActivity extends BaseActivity {

    @BindView(R.id.tv_stime)
    TextView tv_stime;
    @BindView(R.id.tv_etime)
    TextView tv_etime;
    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.recy)
    RecyclerView recy;
    @BindView(R.id.tv_filter)
    TextView tv_filter;
    @BindView(R.id.tv_lxfilter)
    TextView tv_lxfilter;

    List<EventBean.DATA> mData = new ArrayList<>();
    BaseQuickAdapter<EventBean.DATA, BaseViewHolder> mAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_agentmaintenance;
    }

    @Override
    protected void initView() {
        super.initView();
        initToolbarBack(mToolbar);
        mToolbar.setTitle("代维事件");

        String cables = UtilPreferences.getString(mContext,"cable");
        if(cables!=null)
        {
            initTvRightText(mToolbar,"上报",null);
        }

        mRefreshLayout.setColorSchemeResources(R.color.refresh_blue,
                R.color.refresh_red, R.color.refresh_blue, R.color.refresh_red);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData();
            }
        });



        initPicker();
        initPicker1();
        initTimePicker();
        getData();

    }

    @Override
    protected void initData() {
        super.initData();
        tv_lxfilter.setText("外力施工");
        tv_filter.setTag("");
    }

    //region 初始化时间选择器
    private TimePickerView pvSTime;
    private TimePickerView pvETime;
    String sTime = "";
    String eTime = "";

    private void initTimePicker() {

        Calendar endDate = Calendar.getInstance();

        pvSTime = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                tv_stime.setText(DateUtils.dateToString(date, "yyyy-MM-dd"));
                sTime = DateUtils.dateToString(date, "yyyy-MM-dd");
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false}) // 只显示年，月.日
                .setRangDate(null, endDate) // 起始终止年月日设定
                .isDialog(false)
                .build();
        pvSTime.setDate(Calendar.getInstance());


        pvETime = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                tv_etime.setText(DateUtils.dateToString(date, "yyyy-MM-dd"));
                eTime = DateUtils.dateToString(date, "yyyy-MM-dd");
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false}) // 只显示年，月.日
                .setRangDate(null, endDate) // 起始终止年月日设定
                .isDialog(false)
                .build();

        pvETime.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(Object o) {
                if (DateUtils.timeCompare(tv_stime.getText().toString(), tv_etime.getText().toString(), "yyyy-MM-dd") == 1) {
                    ToastUtils.show(mContext, "须 结束时间>开始时间");
                } else {
                    //...
                    getData();
                }
            }
        });
        pvETime.setDate(Calendar.getInstance());

    }
    //endregion

    //region HTTP -- 获取巡查巡检列表
    int page = 1;

    public void getData() {
        page = 1;
        String url = URLUtils.URLNoToken("manageAPI/bizEvent/getPageList");
        Map<String, String> map = new HashMap<>();
        map.put("limit", mContext.getString(R.string.limit));
        map.put("page", "1");
        map.put("type", tv_lxfilter.getText().toString());
        map.put("status", tv_filter.getTag().toString());

        map.put("stm", TextUtils.isEmpty(sTime)? sTime:sTime +" 00:00:00");
        map.put("etm",TextUtils.isEmpty( eTime)? eTime:eTime +" 23:59:59");
//        map.put("army", UtilPreferences.getString(mContext,"army"));
        OkHttpUtils
                .get()
                .url(url)
                .addHeader("Authorization", AccountManager.getToken())
                .params(map)
                .tag(this)
                .build()
                .execute(new ResponseCallback<EventBean>(mContext) {
                    @Override
                    public void onBefore(Request request, int id) {
                        super.onBefore(request, id);
                        mRefreshLayout.setRefreshing(true);
                    }

                    @Override
                    public void onAfter(int id) {
                        super.onAfter(id);
                        mRefreshLayout.setRefreshing(false);
                    }

                    @Override
                    public void onResponse(EventBean response, int id) {
                        super.onResponse(response, id);
                        if (response.code == 0) {
                            if (response.data != null) {
                                mData = response.data;
                            }
                        }  else {
                            if(response.msg != null && "请登录后再访问接口".equals(response.msg))
                            {
                                AppManager.exceptionExitToLogin(mContext, response.msg);
                            }else {
                                ToastUtils.show(mContext, "查询出错");
                            }

                        }

                        if (mAdapter == null) {
                            initRecy();
                        } else {
                            mAdapter.setNewData(mData);
                        }
                    }
                });
    }

    private void loadMore() {
        page = page + 1;
        String url = URLUtils.URLNoToken("manageAPI/bizEvent/getPageList");
        Map<String, String> map = new HashMap<>();
        map.put("limit", mContext.getString(R.string.limit));
        map.put("page", page + "");
        map.put("type", tv_lxfilter.getText().toString());
        map.put("status", tv_filter.getTag().toString());
        map.put("stm",TextUtils.isEmpty(sTime)? sTime:sTime +" 00:00:00");
        map.put("etm",TextUtils.isEmpty( eTime)? eTime:eTime +" 23:59:59");
//        map.put("army", UtilPreferences.getString(mContext,"army"));
        OkHttpUtils
                .get()
                .url(url)
                .addHeader("Authorization", AccountManager.getToken())
                .params(map)
                .tag(this)
                .build()
                .execute(new ResponseCallback<EventBean>(mContext) {
                    @Override
                    public void onResponse(EventBean response, int id) {
                        super.onResponse(response, id);
                        if (response.code == 0) {
                            if (response.data.size() <= 0) {
                                mAdapter.loadMoreEnd();
                            } else {
                                mData.addAll(response.data);
                                mAdapter.loadMoreComplete();
                            }
                        } else {
                            mAdapter.loadMoreEnd();
                        }
                    }

                });
    }
    //endregion

    MyDialog infoDialog;

    //region initRecy
    private void initRecy() {
        mAdapter = new BaseQuickAdapter<EventBean.DATA, BaseViewHolder>(R.layout.list_dwevent_item, mData) {
            @Override
            protected void convert(BaseViewHolder helper, EventBean.DATA item) {
//                TextView tv_num = helper.getView(R.id.tv_num);
//                String num = (helper.getAdapterPosition() + 1) + "";
//                if (num.length() > 2) {
//                    tv_num.setTextSize(12);
//                } else {
//                    tv_num.setTextSize(14);
//                }
//                tv_num.setText(num);

                helper.setText(R.id.tv_bh, item.type)
                        .setText(R.id.tv_zt, ParseUtils.wdrw_new_zt_txt(item.status))
                        .setText(R.id.tv_glzjd, item.cable)
                        .setText(R.id.tv_fqdw, item.createName)
                        .setText(R.id.tv_tm, item.createTime);

                helper.setBackgroundRes(R.id.tv_zt,ParseUtils.wdrw_new_zt_bg(item.status));




            }
        };

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                EventBean.DATA item = mData.get(position);
                Bundle bundle = new Bundle();
                bundle.putSerializable("item", item);
                bundle.putInt("type", 0);
//                openActivity(ReplyEventActivity.class, bundle, false);
                openActivityForResult(ReplyEventActivity.class, bundle,8888);

            }
        });

        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }
        }, recy);

        View emptyView = LayoutInflater.from(mContext).inflate(R.layout.empty_view, null);
        mAdapter.setEmptyView(emptyView);

        recy.setAdapter(mAdapter);
        recy.setLayoutManager(new LinearLayoutManager(mContext));
    }
    //endregion

    OptionsPickerView pvFilter;
    private void initPicker(){
        List<String> list = new ArrayList<>();
        list.add("全部");
        list.add("待派发");
        list.add("待处理");
        list.add("处理中");
        list.add("处理完成");

        pvFilter = new OptionsPickerBuilder(mActivity, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                tv_filter.setText(list.get(options1));
                if(options1 == 0){
                    tv_filter.setTag("");
                }else {
                    tv_filter.setTag(options1-1);
                }

                getData();
            }
        }).build();
        pvFilter.setPicker(list);
    }
    //endregion
    OptionsPickerView pvlxFilter;
    private void initPicker1(){
        List<String> list = new ArrayList<>();
        list.add("外力施工");
        list.add("标准化整治");
        list.add("路由探测");

        pvlxFilter = new OptionsPickerBuilder(mActivity, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                tv_lxfilter.setText(list.get(options1));
                if(options1 == 0){
                    tv_lxfilter.setTag("");
                }else {
                    tv_lxfilter.setTag(options1-1);
                }

                getData();
            }
        }).build();
        pvlxFilter.setPicker(list);
    }
    //endregion

    @OnClick({R.id.tv_stime, R.id.tv_etime,R.id.ll_btn,R.id.ll_lx})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_stime:
                pvSTime.show();
                break;
            case R.id.tv_etime:
                pvETime.show();
                break;
            case R.id.ll_btn:
                pvFilter.show();
                break;
            case R.id.ll_lx:
                pvlxFilter.show();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==8888){
            //处理回调相关操作
            mRefreshLayout.setRefreshing(true);
            getData();
        }
    }

    @Override
    protected void onTvRightClicked() {
        super.onTvRightClicked();

        Bundle bundle = new Bundle();
        openActivityForResult(NewEventCreateActivity.class, bundle,8888);
//        openActivityForResult(TaskReplyActivity.class, bundle,9999);
    }
}